/**
 * @param {Object} options
 * options 默认值
 * {
 *    time: 500, 缩放的时间
 *    width: 1920, 设计图宽度
 *    height: 1080, 设计图高度
 *    container: 'app', 元素的id
 *    type: 1, 缩放的类型， 1 等比缩放 2 宽度站满高度自适应 3 高度站满 宽度自适应 4 宽度高度全部站满
 *    align: 'center', 页面的居中显示 其他字符串顶部对齐
 * }
 *
 * @param {Function} callback 回调函数 (scale) => {} 返回缩放比例
 *
*/
const WHScreenScale = function (options, callback) {

    var scale = 0
    const time = options.time || 500
    const width = options.width || 1920
    const height = options.height || 1080
    const container = options.container || 'app'
    const type = options.type || 1 // 1 width height 2 width 3 height
    const align = options.align || 'center'

    const app = document.getElementById(container)
    app.setAttribute('style', `position: absolute; overflow: hidden; transform-origin: 0 0; left: 50%; top:${align==='center'?'50%':0};transition: 0.3s; width:${width}px; height: ${height}px`)

    function getScale () {
      let ww = window.innerWidth / width
      let wh = window.innerHeight / height
      if (type === 2) {
        return ww
      } else if (type === 3) {
        return wh
      } else if (type === 4) {
        return [ww, wh]
      } else {
        return ww < wh ? ww : wh
      }
    }

    function setScale () {
      scale = getScale()
      callback(scale)
      if (type === 2) {
        app.style.transform = `scaleX(${scale}) translate(-50%, ${align==='center'?'-50%':0})`
      } else if (type === 3) {
        app.style.transform = `scaleY(${scale}) translate(-50%, ${align==='center'?'-50%':0})`
      } else if (type === 4) {
        app.style.transform = `scale(${scale.join(',')}) translate(-50%, ${align==='center'?'-50%':0})`
      } else {
        app.style.transform = `scale(${scale}) translate(-50%, ${align==='center'?'-50%':0})`
      }
    }
    function debounce (fn, delay){

      let timer = null;
      return function () {
        let context = this, args = arguments;
        if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(() => {
          fn.apply(context, args)
        }, delay);
      }
    }

    setScale()
    let debouncedHandler = debounce(setScale, time)
    window.addEventListener('resize', debouncedHandler)
    // 移除监听
    this.clearListener = function () {
      window.removeEventListener('resize', debouncedHandler)
    }
}
export default WHScreenScale
